package com.pqc.tbk.service.taobao;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pqc.tbk.dao.money.MoneyInoutDao;
import com.pqc.tbk.dao.order.OrderDao;
import com.pqc.tbk.dao.user.UserDao;
import com.pqc.tbk.entity.ConstProp;
import com.pqc.tbk.entity.account.User;
import com.pqc.tbk.entity.money.MoneyInout;
import com.pqc.tbk.entity.order.Order;
import com.pqc.tbk.service.TBKServiceException;
import com.pqc.tbk.utils.StringUtil;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeReport;
import com.taobao.api.domain.TaobaokeReportMember;
import com.taobao.api.request.TaobaokeItemsConvertRequest;
import com.taobao.api.request.TaobaokeReportGetRequest;
import com.taobao.api.response.TaobaokeItemsConvertResponse;
import com.taobao.api.response.TaobaokeReportGetResponse;

@Service
@Transactional(readOnly = true)
public class TaoBaoServiceImpl implements TaoBaoService {
	private static final String appkey = "12668380";
	private static final String appsecret = "b8457cfb4a69cdd538e0d4b91a74e553";
	private final static String url = "http://gw.api.taobao.com/router/rest";
	// private final static String appkey = "21020772";
	// private final static String appsecret =
	// "17bab06bb3833f453448664b7c961260";
	private final String me = "ping_qc";

	private OrderDao orderDao;
	private UserDao userDao;
	private MoneyInoutDao moneyInoutDao;

	private static Logger logger = Logger.getLogger(TaoBaoServiceImpl.class);

	private static final TaobaoClient taobao = new DefaultTaobaoClient(url,
			appkey, appsecret, "json");

	@Override
	public List<TaobaokeItem> getTBKItem(final String id, final String outerCode) {
		final TaobaokeItemsConvertRequest req = new TaobaokeItemsConvertRequest();
		req.setNick(me);
		req.setNumIids(id);
		req.setFields("num_iid,title,pic_url,price,click_url,commission,commission_rate,shop_click_url,nick");
		req.setOuterCode(outerCode);
		TaobaokeItemsConvertResponse resp = null;
		try {
			resp = taobao.execute(req);
		}
		catch (final ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resp.getTaobaokeItems();
	}

	@Override
	public TaobaokeReport getReport(final String date, final String top_session) {
		final TaobaokeReportGetRequest request = new TaobaokeReportGetRequest();

		request.setDate(date);
		request.setFields("app_key,category_id,category_name,commission,commission_rate,iid,item_num,item_title,num_iid,outer_code,pay_price,pay_time,real_pay_fee,seller_nick,shop_title,trade_id");
		request.setPageNo(1L);
		request.setPageSize(20L);
		TaobaokeReportGetResponse response = null;
		try {
			response = taobao.execute(request, top_session);
		}
		catch (final ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		final TaobaokeReport report = response.getTaobaokeReport();
		return report;
	}

	@Override
	@Transactional(readOnly = false)
	public void saveReport(final TaobaokeReportMember member) {
		final Order order = new Order();
		order.setCommission(Double.parseDouble(member.getCommission()));// 直接读取设置，
																		// 这里不需要给用户查看
		order.setCommission_rate(Double.parseDouble(member.getCommissionRate()));//
		// 直接读取设置
		order.setItem_num(member.getItemNum());
		order.setItem_title(member.getItemTitle());
		order.setNum_iid(member.getNumIid());
		order.setPay_price(Double.parseDouble(member.getPayPrice()));//
		// 直接读取设置
		order.setPay_time(member.getPayTime());// 直接读取设置
		order.setReal_pay_fee(Double.parseDouble(member.getRealPayFee()));//
		// 直接读取设置
		order.setTrade_id(member.getTradeId());
		String outercode = member.getOuterCode();// 推广者id，
													// 因为outercode可以人为输入，所以需要对其格式进行检查
		if (!StringUtil.isNumeric(outercode)) {
			// 不是数字，即不能转换成对应的用户id，则把此单设定为管理员的订单
			outercode = "1";
		}
		final Long id = Long.parseLong(outercode);
		User user = userDao.findOne(id, User.class);
		if (user == null) {// 用户不存在就把订单转给admin
			user = userDao.findOne(1L, User.class);
		}
		order.setUid(id);
		order.setUser_commission_rate(ConstProp.Promote.BUYER_RETURN_RATE);// 从用户表计算,先设置成70，
																			// 这里是百分比，即70%，
		// 也即把实际返利分50%给推广用户
		// 设置用户可以获得的实际佣金
		order.setUser_commission((order.getCommission() * order
				.getUser_commission_rate()) / 100);// 把user_commission_rate转化成百分比
		orderDao.save(order);

		user.setMoney(user.getMoney() + order.getUser_commission());// 更新用户账户
		user.setMoney_rest(user.getMoney_rest() + order.getUser_commission());
		userDao.update(user);

		// 将用户的更新记录保存
		final MoneyInout moneyInout = new MoneyInout();
		moneyInout.setMoney(order.getUser_commission());
		moneyInout.setType(ConstProp.MoneyInout.IN);// 设置类型为返利
		moneyInout.setUid(id);// 设置用户id
		moneyInoutDao.save(moneyInout);

		if (user.getUserActive() == false) {
			if (user.getInviter_id() != null) {
				setInviterMoney(order.getCommission(), user.getInviter_id(), 2);
			}
			return;
		}

		if (user.getInviter_id() != 1) {
			// 先打钱给第三层次
			setInviterMoney(order.getCommission(), user.getInviter_id(), 1);
			final User user2 = userDao
					.findOne(user.getInviter_id(), User.class);
			if (user2.getInviter_id() != 1) {
				// 打钱给第二层次
				setInviterMoney(order.getCommission(), user2.getInviter_id(), 2);
				final User user3 = userDao.findOne(user2.getInviter_id(),
						User.class);
				if (user3.getInviter_id() != 1) {
					// 打钱给第一层次
					setInviterMoney(order.getCommission(),
							user3.getInviter_id(), 3);
					final User user4 = userDao.findOne(user3.getInviter_id(),
							User.class);
					if (user4.getInviter_id() != 1) {
						logger.info("Error:最上层不是admin");
						throw new TBKServiceException("Error:最上层不是admin");
					}
				}
			}
		}

	}

	private void setInviterMoney(final double commission,
			final Long inviter_id, final int level) {
		// 更新该用户邀请人的账户，推广有奖
		final User inviter = userDao.findOne(inviter_id, User.class);
		final double money = (commission * ConstProp.Promote.LAST_RATE[level]) / 100;// 把用户此笔订单的10%给其邀请人
		if (money >= 0.01) { // 小于1分钱的就不处理了
			inviter.setMoney(inviter.getMoney() + money);// 设置总推广金额和账户余额
			inviter.setMoney_rest(inviter.getMoney_rest() + money);
			final MoneyInout mi = new MoneyInout();// 写入一条记录
			mi.setUid(inviter.getId());
			mi.setMoney(money);
			mi.setType(ConstProp.MoneyInout.PROMOTE);// 推广
			moneyInoutDao.save(mi);
			// TODO 以后可以做成因为邀请用户而获取返利可以进行短消息通知
		}
	}

	@Autowired
	public void setOrderDao(final OrderDao orderDao) {
		this.orderDao = orderDao;
	}

	@Autowired
	public void setUserDao(final UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setMoneyInoutDao(final MoneyInoutDao moneyInoutDao) {
		this.moneyInoutDao = moneyInoutDao;
	}
}
